<template>
  <div class="w100">
    <el-upload
      :action="action"
      accept="image/*"
      :before-remove="beforeRemove"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :data="getReqData"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :show-file-list="false"
    >
      <el-button
        icon="ele-Search"
        :loading="loading"
        type="primary"
      >
        {{ $t("formgen.ocr.identifyingText") }}
      </el-button>
      <template #tip>
        <div class="el-upload__tip">{{ $t("formgen.ocr.tips") }}</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts" name="TOcr">
import { baseUrl } from "@/utils/auth";
import { i18n } from "@/i18n";
import { defineProps, ref, computed, onMounted, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import { formItemProps } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";

const props = defineProps({
  ...formItemProps,
  models: {
    type: Object,
    default: () => {}
  }
});

const fileList = ref<File[]>([]);
const action = ref(baseUrl + "/form/common/ocr");
const loading = ref(false);

const getReqData = computed(() => {
  return {
    type: props.item?.ocrType,
    options: props.item?.options || {}
  };
});

onMounted(() => {
  // Perform any actions that need to happen after component mounts
});

const emits = defineEmits(["ocr-success"]);

const handleRemove = (file: File, fileList: File[]) => {
  console.log(file, fileList);
};

const handlePreview = (file: File) => {
  console.log(file);
};

const handleExceed = () => {
  // Handle exceeding upload limit (if applicable)
};

const beforeRemove = () => {
  // Handle confirmation before removal (if applicable)
};

const handleSuccess = (res: any) => {
  loading.value = false;
  ElMessage.success(i18n.global.t("formI18n.all.success"));

  if (!Object.keys(props.item?.fieldMapping).length) {
    ElMessage.error(i18n.global.t("formgen.ocr.errorMapping"));
    return;
  }

  let values: Record<string, unknown> = {};
  if (res.data) {
    Object.keys(res.data).forEach(key => {
      const modelKey = props.item?.fieldMapping[key];
      values[modelKey] = res.data[key];
    });
  }
  console.log(values);
  emits("ocr-success", values);
};

const handleError = (err: any) => {
  ElMessage.error(err);
  loading.value = false;
};

const handleBeforeUpload = () => {
  loading.value = true;
};
</script>
